package cn.orange.ch08_backtracking;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * LC47.全排列II
 */
public class LC47 {
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        LinkedList<Integer> trace = new LinkedList<>();
        boolean[] visited = new boolean[nums.length];
        Arrays.sort(nums);
        backtracking(nums, visited, trace, ans);
        return ans;
    }

    private void backtracking(int[] nums, boolean[] visited, LinkedList<Integer> trace, List<List<Integer>> ans) {
        if (trace.size() == nums.length) {
            ans.add(new ArrayList<>(trace));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (visited[i]) continue;
            if (i > 0 && nums[i] == nums[i - 1] && !visited[i - 1]) continue;
            visited[i] = true;
            trace.add(nums[i]);
            backtracking(nums, visited, trace, ans);
            trace.removeLast();
            visited[i] = false;
        }
    }

    public static void main(String[] args) {
        LC47 alg = new LC47();
        System.out.println(alg.permuteUnique(new int[]{1, 1, 2}));
        System.out.println(alg.permuteUnique(new int[]{1, 2, 3}));
    }
}
